package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AliPayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;


/**
 * @author gsy
 * @date 2021年09月14日14:22
 * Description 支付宝支付管理
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class AliPayController {
    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    //点击支付宝的扫码支付
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submitAliPay(@PathVariable Long orderId) {
        return aliPayService.submitAliPay(orderId);

    }

    ///同步通知用户  支付成功
    @GetMapping("/callback/return")
    public String callbackReturn() {
        return "redirect:" + AlipayConfig.return_order_url;
    }

    //异步通知商户
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String, String> paramsMap) {
        boolean signVerified = false;//调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // paramsMap
        //{gmt_create=2021-09-15 10:15:36,
        // charset=utf-8,
        // gmt_payment=2021-09-15 10:15:43,
        // notify_time=2021-09-15 10:15:44,
        // subject=Apple iPhone 12 Pro Max (A2412) 256GB 海蓝色 支持移动联通电信5G 双卡双待手机 Apple iPhone 11 (A2223) 64GB 红色 移动联通电信4G,
        // sign=XvhjdkzE3Sw5c6bb5yno0yxx96mX1Q06LjZe1/rFqXG5oQURfLj6A0rJaxhgEpC0NicnuuZwtexuryK6QY7jG17oSh8STujbPWosRr/xHV/b58UP3G5xmc1NJTs6fdueYLSY0K4DmCVWA4Q+BLrUT58jbg3QV6itwxGMzpwsJeT0uIPMc15P137kX35r5+STyLRMVMqD+l5eRtKIWEc/Ni4MGm5Nn9NPQwUHIFQvWwEq9pqbnx/ovtofFC2MF9eT9qLFWnh12ymz36/Il8g2AKc67gbI/4JE0rwruOM1mFtjpi0AhTedhXQMPhN5ZQtDfKUcc5L65t2GAgfxFHfASw==,
        // buyer_id=2088102181130586,
        // body=Apple iPhone 12 Pro Max (A2412) 256GB 海蓝色 支持移动联通电信5G 双卡双待手机 Apple iPhone 11 (A2223) 64GB 红色 移动联通电信4G,
        // invoice_amount=57792.00,
        // version=1.0,
        // notify_id=2021091500222101543030580517434401,
        // fund_bill_list=[{"amount":"57792.00","fundChannel":"ALIPAYACCOUNT"}],
        // notify_type=trade_status_sync,
        // out_trade_no=ATGUIGU1631672105714318,
        // total_amount=57792.00,
        // trade_status=TRADE_SUCCESS,
        // trade_no=2021091522001430580501649117, auth_app_id=2016102100732915, receipt_amount=57792.00, point_amount=0.00, app_id=2016102100732915, buyer_pay_amount=57792.00, sign_type=RSA2, seller_id=2088102180533564}
        if (signVerified) {
            //验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //判断交易状态是否成功
            if ("TRADE_SUCCESS".equals(paramsMap.get("trade_status"))) {
                //查询支付信息
                PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(paramsMap.get("out_trade_no"));
                BigDecimal totalAmount = paymentInfo.getTotalAmount();
                String total_amount = paramsMap.get("total_amount");
                //判断金额是否对的上
                if (total_amount.equals(totalAmount.toString())) {
                    //更新支付表
                    paymentInfoService.updatePaymentInfo(paramsMap);
                    return "success";

                } else {
                    return "failure";
                }
            } else {
                return "success";
            }
        } else {
            //验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
    }

}
